package cn.lg.soar.boot.fc.service.impl;

import cn.lg.soar.boot.client.entity.ClientUser;
import cn.lg.soar.boot.client.service.ClientUserService;
import cn.lg.soar.boot.fc.entity.*;
import cn.lg.soar.boot.fc.entity.Process;
import cn.lg.soar.boot.fc.service.*;
import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.ParameterUtil;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.system.auth.entity.User;
import cn.lg.soar.system.auth.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lg.soar.boot.fc.mapper.ProcessApplyMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户申请审批表
 * @author ZhuanZ（无密码）
 * @since 2025-01-15
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Service
public class ProcessApplyServiceImpl extends ServiceImpl<ProcessApplyMapper, ProcessApply> implements ProcessApplyService {

    @Autowired
    protected IUserService userService;
    @Autowired
    protected ProcessService processService;
    @Autowired
    protected ProcessExamineService processExamineService;
    @Autowired
    protected FormCollectService formCollectService;
    @Resource
    private RoomService roomService;
    @Resource
    private TenancyRoomService tenancyRoomService;
    /** 客户端用户信息服务 */
    @Autowired private ClientUserService clientUserService;

    private SqueryWapper<ProcessApply> squeryWapper;
    /**
     * 用户申请审批(带表单)
     */
    @Transactional
    public HttpResult<Void> apply(ProcessApply addForm,Long roomId,Long leaseId) {
        ParameterUtil.notNull(addForm, "数据不能为空");
//        User user = userService.getById(addForm.getApplicantId());
//        if (null == user){
//            System.out.println("===============1申请用户为空！");
//            return HttpResult.fail("B0000", I18n.build("申请用户为空！"));
//        }
        ClientUser user = clientUserService.getById(addForm.getApplicantId());
        if(user == null) {
            return HttpResult.fail("B0000", I18n.build("申请用户为空！"));
        }
        Process process = processService.getById(addForm.getProcessId());
        if(null == process){
            System.out.println("===============2申请流程为空！");
            return HttpResult.fail("B0000", I18n.build("申请流程为空！"));
        }
        FormCollect formCollect = formCollectService.getById(addForm.getCollectId());
        if (null == formCollect){
            System.out.println("===============1表单收集为空！");
            return HttpResult.fail("B0000", I18n.build("表单收集为空！"));
        }
        if (squeryWapper == null) {
            squeryWapper = new SqueryWapper<>(ProcessApply.class);
        }
        QueryWrapper<ProcessApply> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("processId-eq~"+addForm.getProcessId());
        f.add("applicantId-eq~"+addForm.getApplicantId());
        f.add("customFormId-eq~"+addForm.getCustomFormId());
        f.add("result-eq~0");
        squeryWapper.setWhere(f, wrapper);
        List<ProcessApply> list = super.list(wrapper);
        if(!list.isEmpty()){
            System.out.println("===============3用户申请流程已存在！");
            return HttpResult.fail("B0000", I18n.build("用户申请流程已存在！"));
        }
        LocalDateTime now = LocalDateTime.now();
        addForm.setResult(0);
        addForm.setApplyTime(now);
        AssertUtil.isTrue(super.save(addForm), "创建失败");

//        list = super.list(wrapper);

        // 申请租房
        if(formCollect.getVisibleRange() == 1){
            if(roomId == null){
                System.out.println("===============1房间ID为空！");
                return HttpResult.fail("B0000", I18n.build("房间ID为空！"));
            }
            Room room = roomService.getById(roomId);
            if (null == room){
                System.out.println("===============1房间信息为空！");
                return HttpResult.fail("B0000", I18n.build("房间信息为空！"));
            }
            if(room.getTenancyWay() == 1 && leaseId == null){
                System.out.println("===============1合租ID为空！");
                return HttpResult.fail("B0000", I18n.build("合租ID为空！"));
            }
            tenancyRoomService.applyRoom(addForm.getCustomFormId(), roomId, leaseId, addForm.getId());
        }
        return processExamineService.examineApply(addForm.getId(),process.getId(), addForm.getApplicantId(),now,
                addForm.getCustomFormId(),addForm.getCollectId(),addForm.getUserId());
    }

    /**
     * 用户申请审批(不带表单)
     */
    @Transactional
    public HttpResult<Void> applyExamine(ProcessApply addForm) {
        ParameterUtil.notNull(addForm, "数据不能为空");
//        User user = userService.getById(addForm.getApplicantId());
//        if (null == user){
//            System.out.println("===============1申请用户为空！");
//            return HttpResult.fail("B0000", I18n.build("申请用户为空！"));
//        }
        ClientUser user = clientUserService.getById(addForm.getApplicantId());
        if(user == null) {
            return HttpResult.fail("B0000", I18n.build("申请用户为空！"));
        }
        Process process = processService.getById(addForm.getProcessId());
        if(null == process){
            System.out.println("===============2申请流程为空！");
            return HttpResult.fail("B0000", I18n.build("申请流程为空！"));
        }
        LocalDateTime now = LocalDateTime.now();
        addForm.setResult(0);
        addForm.setApplyTime(now);
        AssertUtil.isTrue(super.save(addForm), "创建失败");
        if (squeryWapper == null) {
            squeryWapper = new SqueryWapper<>(ProcessApply.class);
        }
        QueryWrapper<ProcessApply> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("processId-eq~"+addForm.getProcessId());
        f.add("applicantId-eq~"+addForm.getApplicantId());
        f.add("result-eq~0");
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-applyTime");
        squeryWapper.setWhere(f, wrapper);
        squeryWapper.setOrderBy(orderBy, wrapper);
        List<ProcessApply> list = super.list(wrapper);

        return processExamineService.examineApply(list.get(0).getId(),process.getId(), addForm.getApplicantId(),now,
                null,null,addForm.getUserId());
    }

}
